package com.ifnk.portaljava.hlyt.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
/**
 * <p>Title:接收上传文件的servlet类</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: </p>
 *
 * @author  xiaoyan.zhang.hlyt@gmail.com
 * @version 1.0
 */
public class ReceiveFileServlet extends HttpServlet {

	// 限制文件的上传大小

	/**
	 * 
	 */
	private static final long serialVersionUID = 6867945366595015409L;
	//private int maxPostSize = 1024 * 1024 * 1024;

	public ReceiveFileServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Locale locale = Locale.ENGLISH;
		ResourceBundle localResource = ResourceBundle.getBundle("filePath",locale);
		String uploadPath = localResource.getString("uploadDirectoryPath");
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		
		//PrintWriter out = response.getWriter();
		
		// 保存文件到服务器中

		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(4096);
		ServletFileUpload upload = new ServletFileUpload(factory);
//		upload.setSizeMax(maxPostSize);
		try {
			List fileItems = upload.parseRequest(request);
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					String name = new String(item.getName().getBytes(), "UTF-8");
					try {
						name = uploadPath + name;
						item.write(new File(name));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	public String getServletInfo() {
		return "Short description";
	}
}
